package main

import (
	"Go-Easy/microservice/helloworld/proto"
	"Go-Easy/pkg/microservice/interceptor"
	"Go-Easy/pkg/microservice/service"
	"context"
	"errors"
	"google.golang.org/grpc"
	"google.golang.org/grpc/metadata"
	"log"
)

//继承HelloServiceServer
type Server struct {
	pb.HelloServiceServer
}

//override父类方法
func (s Server) Hello(c context.Context, r *pb.HelloRequest) (*pb.HelloResponse, error) {
	return &pb.HelloResponse{Result: r.Message}, nil
}

//身份验证方法
func Authentication(ctx context.Context) error {
	if m, ok := metadata.FromIncomingContext(ctx); ok {
		log.Print("metadata:", m)
		if len(m.Get("Token")) > 0 {
			if m.Get("Token")[0] == "DHNFk" {
				return nil
			}
		}
	}
	return errors.New("用户校验失败")
}

func main() {
	easyInterceptor := interceptor.NewEasyInterceptor("Hello", Authentication)
	easyService := service.NewEasyService("Hello", grpc.UnaryInterceptor(easyInterceptor.UnaryInterceptor()))
	if grpcServer, err := easyService.CreateNewServer(); err == nil {
		pb.RegisterHelloServiceServer(grpcServer, Server{}) //注册服务
		easyService.RunService(grpcServer)                  //运行服务
	} else {
		panic(err)
	}
}
